import time
import datetime
from urllib.parse import quote
import re
def trans_time(date):
    date = date.replace('年', '-').replace('月', '-').replace('日', '')
    if '分钟前' in date:
        now_ts = time.time()
        minute = int(date.rstrip(u'分钟前'))
        ts = now_ts - minute * 60
    elif '小时前' in date:
        now_ts = time.time()
        hour = int(date.rstrip(u'小时前'))
        ts = now_ts - hour * 3600
    elif '天前' in date:
        now_ts = time.time()
        day = int(date.rstrip(u'天前'))
        ts = now_ts - day * 86400
    else:
        datetime_re = re.findall(
            r'\d+-\d+-\d+', date)[0]
        timeArray = time.strptime(datetime_re, "%Y-%m-%d")
        ts = time.mktime(timeArray)
    date = time.strftime('%Y-%m-%d', time.localtime(int(ts)))
    return int(ts),date

def generate_url(keyword, start_time, end_time):
    y0 = start_time.split('-')[0]
    y1 = end_time.split('-')[0]
    cha1 = Caltime('1970-1-1', start_time)
    cha2 = Caltime('1970-1-1', end_time)
    bt = cha1 * 86400 - 28800
    et = cha2 * 86400 - 28800 + 86399
    url = 'http://news.baidu.com/ns?word={keyword}&cl=2&ct=0&tn=newsdy&rn=50&ie=utf-8&bt={bt}&et={et}'.format(
        keyword=keyword, bt=bt, et=et)
    return url

def Caltime(date1, date2):
    # 计算两个日期相差天数，自定义函数名，和两个日期的变量名。
    date1 = time.strptime(date1, "%Y-%m-%d")
    date2 = time.strptime(date2, "%Y-%m-%d")
    date1 = datetime.datetime(date1[0], date1[1], date1[2])
    date2 = datetime.datetime(date2[0], date2[1], date2[2])
    # 返回两个变量相差的值，就是相差天数
    # 当date2日期晚于date1日期,结果为正值
    # 反之,返回结果为负值
    return (date2 - date1).days

def sub(string):
    sub_str = '[\r\n\t\xa0\u3000 ]'
    new_string = re.sub(sub_str, '', string).strip()
    return new_string